﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using StyleMVVM.DependencyInjection;

namespace StyleMVVM.ViewModel.Impl
{
	public class ViewModelWindowBinder : IViewModelBinder
	{
		private static string supplemental = typeof(ViewModelWindowBinder).FullName;

		public static void RegisterExport(IDependencyInjectionContainer container)
		{
			container.Register(typeof(ViewModelWindowBinder)).As(typeof(IViewModelBinder));
		}

		public void BindViewModelToView(FrameworkElement frameworkElement, object viewModel)
		{
			Window window = frameworkElement as Window;
			IWindowViewModel windowViewModel = viewModel as IWindowViewModel;

			if (windowViewModel != null && window != null)
			{
				window.Closing += WindowOnClosing;
				window.Closed += WindowOnClosed;
			}
		}

		private void WindowOnClosed(object sender, EventArgs eventArgs)
		{
			Window window = sender as Window;

			if (window != null)
			{
				IWindowViewModel viewModel = window.DataContext as IWindowViewModel;

				if (viewModel != null)
				{
					viewModel.Closed();
				}
			}
		}

		private static void WindowOnClosing(object sender, CancelEventArgs cancelEventArgs)
		{
			Window window = sender as Window;

			if (window != null)
			{
				IWindowViewModel viewModel = window.DataContext as IWindowViewModel;

				if (viewModel != null)
				{
					viewModel.Closing(cancelEventArgs);
				}
			}
		}

		public void UnbindViewModelFromView(FrameworkElement frameworkElement, object viewModel)
		{
			Window window = frameworkElement as Window;
			IWindowViewModel windowViewModel = viewModel as IWindowViewModel;

			if (windowViewModel != null && window != null)
			{
				window.Closing -= WindowOnClosing;
				window.Closed -= WindowOnClosed;
			}
		}
	}
}